
class ListNode {
     int val;
     ListNode next;
     ListNode(int x) {
         val = x;
         next = null;
     }
}

class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null){
            return null;
        }

        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow){
                slow = head;
                break;
            }
        }
        if(fast == null || fast.next == null){
            return null;
        }
        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}